import {pushTarget,popTarget} from './dep.js'
let id=0
class Watch {
    constructor(vm,exprOrFn,callback,options){
        this.id=id++
        this.vm=vm
        this.callback=callback
        this.options=options
        this.getter=exprOrFn
        this.depId=[]
        this.subDep=[]
        this.get()
        
    }
    get(){
        pushTarget(this)  //让dep收集依赖watcher
        this.getter()
        popTarget()      //更新完释放依赖
    }
    update(){
        queueWatcher(this)
    }
    run(){
        this.get()
    }
    addDep(dep){
        //一个watcher 要存多个dep（属性）
        //做去重，即一个组件只有一个watch，watch里存在组件中的所有属性
        if(!this.depId.includes(dep.id)){
            this.subDep.push(dep)  //收集dep属性
            this.depId.push(dep.id)
            dep.addSub(this)
            console.log(this.subDep,'dep-------收集器')
        }
    }
    
}
let has={}
let queue=[]
function queueWatcher(watcher){
    if(!has[watcher.id]){
        queue.push(watcher)
        has[watcher.id]=true
        //异步执行  相同的属性视图更新
        nextTick(()=>{
            queue.forEach(watcher=>watcher.run())
            has[watcher.id]=null
            queue=[]
         })
     }
   
}
let callback=[]
let isUpdate=false
export function nextTick(cb){
    callback.push(cb)
    setTimeout(()=>{
        isUpdate=true
        if(isUpdate){
            //在更新过程不会重复执行
            callback.forEach(cbk=>{
                cbk()
                callback=[]
                isUpdate=false
            })
        }
        
    })
}

export default Watch